﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace UserEvaluationStudy
{
    public partial class panelModelSuggestionStudy : Form
    {
        //String parametersFilename = @"C:\Users\Laureen\code\UserEvaluationStudy\Parameters.txt";
        //String parametersFilename = "../../Parameters.txt";

        // TODO: Uncomment out the following line for the final User Eval build (this will allow users to run this program locally)
        String parametersFilename = "Parameters.txt";

        String userTestDataFilename;
        String sceneScreenshotsPath;
        String imageModelsPath;

        // currentPage can range from 1 to pageCount
        int currentPage;

        // pageList indices are 0 to pageCount-1
        List<Page> pageList = new List<Page>();

        //List<String> allButtonLabels = new List<String>();
        //List<String> allSuggestionButtons = new List<String>();

        List<Button> allButtons = new List<Button>();
        List<Label> allButtonLabels = new List<Label>();

        class Page
        {
            public int pageNum;

            public String sceneScreenshotFilename;
            public String originalModelId;
            public List<ReplacementModel> replacements;
        };

        class ReplacementModel
        {
            public int suggestionType;
            public String modelId;
            public bool isSelected;
        };

    // ====================================================================================

        public panelModelSuggestionStudy()
        {
            InitializeComponent();

            // This also loads the last saved test data
            // (The test data file is specified in Parameters.txt, 1st line)
            LoadParameterFile();

            // render the starting page
            UpdateSelectedPage();
        }

        private void UserStudy_FormClosing(object sender, FormClosingEventArgs e)
        {
            SaveUserData();
        }

        private void SaveUserData()
        {
            StreamWriter writer = File.CreateText(userTestDataFilename);

            // save last page number
            writer.WriteLine(currentPage);

            // and rest of data
            foreach (Page page in pageList)
            {
                writer.Write(page.pageNum + "^");
                writer.Write(page.sceneScreenshotFilename + "|" + page.originalModelId + "|");

                for (int i = 0; i < page.replacements.Count; i++)
                {
                    ReplacementModel model = page.replacements[i];
                    if (model.suggestionType == 0)
                    {
                        writer.Write("R:");
                    }
                    else if (model.suggestionType == 1)
                    {
                        writer.Write("S:");
                    }
                    else if (model.suggestionType == 2)
                    {
                        writer.Write("M:");
                    }

                    if (model.isSelected)
                    {
                        writer.Write("Y:");
                    }
                    else
                    {
                        writer.Write("N:");
                    }

                    writer.Write(model.modelId);

                    if (i != page.replacements.Count - 1)
                    {
                        writer.Write("|");
                    }

                }

                //if (o.cat != null)
                //{
                //    writer.WriteLine(o.sceneName + "@" + o.sceneObjectIndex + "@" + o.cat.name);
                //}
                writer.WriteLine();
            }
            writer.Close();

        }

        private void LoadParameterFile()
        {
            String[] parameterLines;

            if (File.Exists(parametersFilename))
            {
                parameterLines = File.ReadAllLines(parametersFilename);
            }
            else
            {
                parameterLines = File.ReadAllLines("Parameters.txt");
            }

            userTestDataFilename = parameterLines[0];
            sceneScreenshotsPath = parameterLines[1];
            imageModelsPath = parameterLines[2];

            //labelDebugOutput.Text = "Loading user test datafile: " + userTestDataFilename;

            if (File.Exists(userTestDataFilename))
            {
                String[] testDataFileLines = File.ReadAllLines(userTestDataFilename);

                // Load user test data
                if (testDataFileLines[0].Length > 0)
                {
                    currentPage = Convert.ToInt32(testDataFileLines[0]);
                    //labelDebugOutput.Text = "current page: " + currentPage;
                }
                //int pageCount = 0;
                for (int lineIndex = 1; lineIndex < testDataFileLines.Length; lineIndex++)
                {
                    if (testDataFileLines[lineIndex].Length > 0)
                    {
                        AddTestPage(testDataFileLines[lineIndex]);
                        //pageCount++;
                    }
                }
                //labelDebugOutput.Text = "numPages: " + pageCount;
            }
        }

        private void AddTestPage(String testData)
        {
            String[] firstSplit = testData.Split('^');
            if (firstSplit.Length > 0)
            {
                //labelDebugOutput.Text = "Split length " + firstSplit.Length;
                Page newPage = new Page();

                newPage.pageNum = Convert.ToInt32(firstSplit[0]);
                //labelDebugOutput.Text = "pageNumber loaded " + Convert.ToInt32(firstSplit[0]);

                String[] words = firstSplit[1].Split('|');
                newPage.sceneScreenshotFilename = words[0];
                newPage.originalModelId = words[1];
                //labelDebugOutput.Text = "originalModelId  " + newPage.originalModelId;

                List<ReplacementModel> replacementModels = new List<ReplacementModel>();
                for (int i = 2; i < words.Length; i++)
                {
                    String[] suggestionData = words[i].Split(':');

                    ReplacementModel replacement = new ReplacementModel();
                    if (String.Compare("R", suggestionData[0], true) == 0)
                    {
                        replacement.suggestionType = 0;
                    }
                    else if (String.Compare("S", suggestionData[0], true) == 0)
                    {
                        replacement.suggestionType = 1;
                    }
                    else if (String.Compare("M", suggestionData[0], true) == 0)
                    {
                        replacement.suggestionType = 2;
                    }

                    if (String.Compare("Y", suggestionData[1], true) == 0)
                    {
                        replacement.isSelected = true;
                    }
                    else
                    {
                        replacement.isSelected = false;
                    }

                    replacement.modelId = suggestionData[2];

                    replacementModels.Add(replacement);
                } // for() each replacement model

                newPage.replacements = replacementModels;
                pageList.Add(newPage);
            }
        }

        private void UpdateSelectedPage()
        {
            labelPageIndex.Text = "Page " + currentPage + " / " + pageList.Count;
            //labelDebugOutput.Text = "replacement modelId  " + replacement.modelId;

            // Render rest of page:
            Page currPage = pageList[currentPage-1];

            Image scaledScene = ResizeImage(sceneScreenshotsPath + currPage.sceneScreenshotFilename, pictureSceneScreenshot.Width, pictureSceneScreenshot.Height, false);
            pictureSceneScreenshot.Image = scaledScene;
            //Image scaledOriginalModel = ResizeImage(imageModelsPath + currPage.originalModelId + ".jpg", pictureOriginalModel.Width, pictureOriginalModel.Height, false);
            //pictureOriginalModel.Image = scaledOriginalModel;

            // Render button images
            updateSuggestionButtons(currPage);
        }

        private void updateSuggestionButtons(Page currPage)
        {
            Image suggestion1 = ResizeImage(imageModelsPath + currPage.replacements[0].modelId + ".jpg", buttonSuggestion1.Width, buttonSuggestion1.Height, false);
            buttonSuggestion1.Image = suggestion1;
            if (currPage.replacements[0].isSelected)
            {
                //labelDebugOutput.Text = "replacement model 0 is selected";

                // Updating the checkbox MUST be done first (for some stupid reason)
                //checkBoxSuggestion1.Checked = true;
                labelSelected1.Visible = true;
            }
            else
            {
                //checkBoxSuggestion1.Checked = false;
                labelSelected1.Visible = false;
            }

            Image suggestion2 = ResizeImage(imageModelsPath + currPage.replacements[1].modelId + ".jpg", buttonSuggestion2.Width, buttonSuggestion2.Height, false);
            buttonSuggestion2.Image = suggestion2;
            if (currPage.replacements[1].isSelected)
            {
                //checkBoxSuggestion2.Checked = true;
                labelSelected2.Visible = true;
            }
            else
            {
                //checkBoxSuggestion2.Checked = false;
                labelSelected2.Visible = false;
            }

            Image suggestion3 = ResizeImage(imageModelsPath + currPage.replacements[2].modelId + ".jpg", buttonSuggestion3.Width, buttonSuggestion3.Height, false);
            buttonSuggestion3.Image = suggestion3;
            if (currPage.replacements[2].isSelected)
            {
                //checkBoxSuggestion3.Checked = true;
                labelSelected3.Visible = true;
            }
            else
            {
                //checkBoxSuggestion3.Checked = false;
                labelSelected3.Visible = false;
            }

            Image suggestion4 = ResizeImage(imageModelsPath + currPage.replacements[3].modelId + ".jpg", buttonSuggestion4.Width, buttonSuggestion4.Height, false);
            buttonSuggestion4.Image = suggestion4;
            if (currPage.replacements[3].isSelected)
            {
                //checkBoxSuggestion4.Checked = true;
                labelSelected4.Visible = true;
            }
            else
            {
                //checkBoxSuggestion4.Checked = false;
                labelSelected4.Visible = false;
            }

            Image suggestion5 = ResizeImage(imageModelsPath + currPage.replacements[4].modelId + ".jpg", buttonSuggestion5.Width, buttonSuggestion5.Height, false);
            buttonSuggestion5.Image = suggestion5;
            if (currPage.replacements[4].isSelected)
            {
                //checkBoxSuggestion5.Checked = true;
                labelSelected5.Visible = true;
            }
            else
            {
                //checkBoxSuggestion5.Checked = false;
                labelSelected5.Visible = false;
            }

            Image suggestion6 = ResizeImage(imageModelsPath + currPage.replacements[5].modelId + ".jpg", buttonSuggestion6.Width, buttonSuggestion6.Height, false);
            buttonSuggestion6.Image = suggestion6;
            if (currPage.replacements[5].isSelected)
            {
                //checkBoxSuggestion6.Checked = true;
                labelSelected6.Visible = true;
            }
            else
            {
                //checkBoxSuggestion6.Checked = false;
                labelSelected6.Visible = false;
            }
        }

        private void prevButton_Click(object sender, EventArgs e)
        {
            currentPage--;
            if (currentPage <= 0) currentPage = pageList.Count;
            UpdateSelectedPage();
        }

        private void nextButton_Click(object sender, EventArgs e)
        {
            currentPage++;
            if (currentPage > pageList.Count && pageList.Count != 0) currentPage = 1;
            else if (currentPage > pageList.Count && pageList.Count == 0) currentPage = 0;

            UpdateSelectedPage();
        }

        private void panelModelSuggestionStudy_Load(object sender, EventArgs e)
        {

        }

        public Image ResizeImage(string OriginalFile, int NewWidth, int MaxHeight, bool OnlyResizeIfWider)
        {
            Image FullsizeImage = System.Drawing.Image.FromFile(OriginalFile);

            // Prevent using images internal thumbnail
            FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
            FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);

            if (OnlyResizeIfWider)
            {
                if (FullsizeImage.Width <= NewWidth)
                {
                    NewWidth = FullsizeImage.Width;
                }
            }

            int NewHeight = FullsizeImage.Height * NewWidth / FullsizeImage.Width;
            if (NewHeight > MaxHeight)
            {
                // Resize with height instead
                NewWidth = FullsizeImage.Width * MaxHeight / FullsizeImage.Height;
                NewHeight = MaxHeight;
            }

            System.Drawing.Image NewImage = FullsizeImage.GetThumbnailImage(NewWidth, NewHeight, null, IntPtr.Zero);

            return NewImage;

            //// Clear handle to original file so that we can overwrite it if necessary
            //FullsizeImage.Dispose();

            //// Save resized picture
            //NewImage.Save(NewFile);
        }

        private void buttonSuggestion1_Click(object sender, EventArgs e)
        {
            Page currPage = pageList[currentPage-1];
            if (labelSelected1.Visible == true)
            {
                // For some reason, this needs to come before altering label properties
                //checkBoxSuggestion1.Checked = false;

                labelSelected1.Visible = false;
                currPage.replacements[0].isSelected = false;
            }
            else
            {
                //checkBoxSuggestion1.Checked = true;

                labelSelected1.Visible = true;
                currPage.replacements[0].isSelected = true;
            }
        }

        private void buttonSuggestion2_Click(object sender, EventArgs e)
        {
            Page currPage = pageList[currentPage - 1];
            if (labelSelected2.Visible == true)
            {
                //checkBoxSuggestion2.Checked = false;

                labelSelected2.Visible = false;
                currPage.replacements[1].isSelected = false;
            }
            else
            {
                //checkBoxSuggestion2.Checked = true;

                labelSelected2.Visible = true;
                currPage.replacements[1].isSelected = true;
            }
        }

        private void buttonSuggestion3_Click(object sender, EventArgs e)
        {
            Page currPage = pageList[currentPage - 1];
            if (labelSelected3.Visible == true)
            {
                //checkBoxSuggestion3.Checked = false;

                labelSelected3.Visible = false;
                currPage.replacements[2].isSelected = false;
            }
            else
            {
                //checkBoxSuggestion3.Checked = true;

                labelSelected3.Visible = true;
                currPage.replacements[2].isSelected = true;
            }
        }

        private void buttonSuggestion4_Click(object sender, EventArgs e)
        {
            Page currPage = pageList[currentPage - 1];
            if (labelSelected4.Visible == true)
            {
                //checkBoxSuggestion4.Checked = false;

                labelSelected4.Visible = false;
                currPage.replacements[3].isSelected = false;
            }
            else
            {
                //checkBoxSuggestion4.Checked = true;

                labelSelected4.Visible = true;
                currPage.replacements[3].isSelected = true;
            }
        }

        private void buttonSuggestion5_Click(object sender, EventArgs e)
        {
            Page currPage = pageList[currentPage - 1];
            if (labelSelected5.Visible == true)
            {
                //checkBoxSuggestion5.Checked = false;

                labelSelected5.Visible = false;
                currPage.replacements[4].isSelected = false;
            }
            else
            {
                //checkBoxSuggestion5.Checked = true;

                labelSelected5.Visible = true;
                currPage.replacements[4].isSelected = true;
            }
        }

        private void buttonSuggestion6_Click(object sender, EventArgs e)
        {
            Page currPage = pageList[currentPage - 1];
            if (labelSelected6.Visible == true)
            {
                //checkBoxSuggestion6.Checked = false;

                labelSelected6.Visible = false;
                currPage.replacements[5].isSelected = false;
            }
            else
            {
                //checkBoxSuggestion6.Checked = true;

                labelSelected6.Visible = true;
                currPage.replacements[5].isSelected = true;
            }
        }

        //private void checkBoxSuggestion1_CheckedChanged(object sender, EventArgs e)
        //{
        //    buttonSuggestion1_Click(sender, e);
        //}

        //private void checkBoxSuggestion2_CheckedChanged(object sender, EventArgs e)
        //{
        //    buttonSuggestion2_Click(sender, e);
        //}

        //private void checkBoxSuggestion3_CheckedChanged(object sender, EventArgs e)
        //{
        //    buttonSuggestion3_Click(sender, e);
        //}

        //private void checkBoxSuggestion4_CheckedChanged(object sender, EventArgs e)
        //{
        //    buttonSuggestion4_Click(sender, e);
        //}

        //private void checkBoxSuggestion5_CheckedChanged(object sender, EventArgs e)
        //{
        //    buttonSuggestion5_Click(sender, e);
        //}

        //private void checkBoxSuggestion6_CheckedChanged(object sender, EventArgs e)
        //{
        //    buttonSuggestion6_Click(sender, e);
        //}

    }
}
